package cn.hh.wechatkit.api.token;

import cn.hh.wechatkit.exception.Wx_Exception_InvalidJsonParse;
import cn.hh.wechatkit.exception.Wx_Exception_InvalidResponse;
import cn.hh.wechatkit.param.WxParam;
import cn.hh.wechatkit.pojo.token.WxToken_AccessToken;
import cn.hhchat.kit.http.httpUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Headers;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import static cn.hh.wechatkit.helper.WxConst.AccessToken_GET_URL;

/**
 * Created by HMH on 2017/3/23.
 * 获取config Access_Token
 */
@Slf4j
public class WxAPI_Access_Token_Api {

    private static Logger logger = LoggerFactory.getLogger(WxAPI_Access_Token_Api.class);

    //get请求，获取access_token
    public static WxToken_AccessToken getAccess_token(String appID, String appsecret) {
        String url = AccessToken_GET_URL.replace("APPID", appID).replace("APPSECRET", appsecret);
        Response response = null;
        try {
            response = httpUtil.get(url);
            if (response != null) {
                try {
                    Headers headers = response.headers();
                    String body = response.body().string();
                    //解析字符串
                    WxToken_AccessToken wxAccessToken = JSON.parseObject(body, WxToken_AccessToken.class);
                    wxAccessToken.setExpires_time(wxAccessToken.getExpires_in() * 1000 + headers.getDate("date").getTime() - WxParam.expireTimeAhead);
                    return wxAccessToken;
                } catch (IOException e) {
                    log.error("处理返回的AccessToken发生错误\n",e);
                    throw new Wx_Exception_InvalidJsonParse("处理返回的AccessToken发生错误\n", e);
                }
            }
        } catch (IOException e) {
            log.error("accessToken接口请求失败");
        }
        throw new Wx_Exception_InvalidResponse("没有收到响应，或者请求出错");
    }
}
